import "dart:convert";
import "dart:developer";
import 'package:alipay_kit/alipay_kit.dart';
import 'package:ball_lion/module/mine/my_purchase_logic.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/match/secret_price_entity.dart';
import 'package:ball_lion/entity/pay/my_coupon.dart';
import 'package:ball_lion/entity/my/order_list_entity.dart';
import 'package:ball_lion/entity/pay/usable_coupon.dart';
import 'package:ball_lion/entity/pay/coin_detail_entity.dart';
import 'package:ball_lion/entity/pay/coin_history_entity.dart';
import 'package:ball_lion/entity/pay/recharge_entity.dart';
import 'package:ball_lion/utils/web_pay.dart';
import 'package:ball_lion/module/pay/pay_bottom_sheet.dart';
import 'package:ball_lion/entity/ai/ai_pay_entity.dart';
import 'package:ball_lion/entity/pay/subscribe_entity.dart';
import 'package:ball_lion/entity/vip/vip_pay_entity.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import '../api_dir.dart';
import '../http/dio_utils.dart';

class PayApi {
  //status
  //0 表示 已过期 或 已使用 的券
  //1 表示 可使用 或 待生效 的券
  static Future<List<MyCouponEntity>?> myCoupons({int status = 1}) async {
    try {
      final response = await DioUtils.post(
          "/${ApiDir.user}/usr-coupon-do/myCouponList",
          params: {"status": status, "userId": User.auth?.userId});
      return (response.data["d"] as List)
          .map((e) => MyCouponEntity.fromJson(e))
          .toList();
    } catch (err) {}
    return null;
  }

  //gold 优惠前价格
  //scene 1 购买方案
  //otherId 购买方案传专家id
  static Future<List<UsableCouponEntity>?> useCoupons(
      {required double gold, required String otherId, int scene = 1}) async {
    try {
      final response = await DioUtils.post(
          "/${ApiDir.user}/usr-coupon-do/canUseCouponList",
          params: {
            "gold": gold,
            "otherId": otherId,
            "scene": scene,
            "userId": User.auth?.userId
          });
      return (response.data["d"] as List)
          .map((e) => UsableCouponEntity.fromJson(e))
          .toList();
    } catch (err) {
      log("use1 coupon err $err");
    }
    return null;
  }

  //购买方案
  static Future planOrder(double gold, String planId,
      {double? couponGold,
      String? couponId,
      int? roomId,
      String? subsId}) async {
    try {
      final result = await DioUtils.post("/${ApiDir.plan}/app-plan-do/order",
          params: {
            "gold": gold,
            "planId": planId,
            "userId": User.auth?.userId,
            "couponGold": couponGold,
            "couponId": couponId,
            "subsId": subsId,
            "roomId": roomId
          },
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("解锁成功");
        return true;
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(const QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Toast.text(result.data["m"]);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("解锁失败，请重试");
    }
  }

  ///订阅支付
  static Future subsOrder(double gold, String expertId,
      {double? couponGold,
      int? couponId,
      String? seq,
      int? subsType,
      int? roomId}) async {
    try {
      final result = await DioUtils.post("/${ApiDir.plan}/app-idea/expertSubs",
          params: {
            "gold": gold,
            "expertId": expertId,
            "couponGold": couponGold,
            "couponId": couponId,
            "seq": seq,
            "subsType": subsType,
            "roomId": roomId
          },
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("订阅成功");
        Utils.onEvent("dyxq_zfyd_qrzf");
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Utils.onEvent("dyxq_zfyd_qxzf");
        Toast.text(result.data["m"]);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("订阅失败，请重试");
    }
  }

  static Future<List<SubscribleCardEntity>?> querySubCards(
      String expertId) async {
    try {
      final response = await DioUtils.post("/${ApiDir.plan}/app-idea/subList/",
          params: expertId);
      return (response.data["d"] as List)
          .map((e) => SubscribleCardEntity.fromJson(e))
          .toList();
    } catch (err) {
      log("subscrible cards $err");
    }
    return [];
  }

  ///ai支付
  static Future aiOrder(int? priceId,
      {double? couponGold, int? couponId, int? aiId, int? roomId}) async {
    try {
      final result = await DioUtils.post("/${ApiDir.ai}/app-ai-order/pay",
          params: {
            "priceId": priceId,
            "couponGold": couponGold,
            "couponId": couponId,
            "aiId": aiId,
            "roomId": roomId
          },
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("购买成功");
        return true;
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Toast.text(result.data['m']);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("购买失败，请重试");
    }
  }

  ///ai组合支付
  static Future aiPackOrder(List<int>? priceId, {int? roomId}) async {
    try {
      final result = await DioUtils.post(
          "/${ApiDir.ai}/app-ai-order/payMultiple",
          params: {"priceId": priceId, "roomId": roomId},
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("购买成功");
        return true;
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Toast.text(result.data['m']);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("购买失败，请重试");
    }
  }

  ///vip支付
  static Future vipOrder(int? priceId,
      {double? couponGold, int? couponId, int? roomId}) async {
    try {
      final result = await DioUtils.post("/${ApiDir.user}/app-user-vip/pay",
          params: {
            "priceId": priceId,
            "couponGold": couponGold,
            "couponId": couponId,
            "roomId": roomId
          },
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("${User.info?.isVip == 0 ? "开通" : "续费"}成功");
        return true;
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Toast.text(result.data["m"]);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("${User.info?.isVip == 0 ? "开通" : "续费"}失败，请重试");
    }
  }

  ///海外情报支付
  static Future secretOrder(int? priceId,
      {double? couponGold, int? couponId, int? roomId}) async {
    try {
      final result = await DioUtils.post("/${ApiDir.info}/app-reveal/order",
          params: {
            "priceId": priceId,
            "couponGold": couponGold,
            "couponId": couponId,
            "roomId": roomId
          },
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("购买成功");
        return true;
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Toast.text(result.data["m"]);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("购买失败，请重试");
    }
  }

  ///计划单支付
  static Future planFormOrder(int? issueId, double gold,
      {double? couponGold, int? couponId, int? roomId}) async {
    try {
      final result = await DioUtils.post("/${ApiDir.plan}/app-plan-list/order",
          params: {
            "pay": gold,
            "issueId": issueId,
            "couponGold": couponGold,
            "couponId": couponId,
            "roomId": roomId
          },
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("购买成功");
        return true;
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Toast.text(result.data['m']);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("购买失败，请重试");
    }
  }

  ///券包支付
  static Future couponPackOrder(int? id, {int? roomId}) async {
    try {
      final result = await DioUtils.post(
          "/${ApiDir.activity}/app-act-goods-group-do/payPackage",
          params: {"id": id, 'userId': User.info?.id, "roomId": roomId},
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("购买成功");
        return true;
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Toast.text(result.data['m']);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("购买失败，请重试");
    }
  }

  ///方案套餐支付
  static Future planPackOrder(int? id) async {
    try {
      final result = await DioUtils.post(
          "/${ApiDir.plan}/app-pl-package-do/payPackage",
          params: {"id": id, 'userId': User.info?.id},
          showLoading: true,
          showToast: false);
      if (result.data["c"] == 200) {
        await Future.delayed(const Duration(milliseconds: 500));
        Toast.text("购买成功");
        return true;
      } else if (result.data["c"] == 1002) {
        await Future.delayed(const Duration(milliseconds: 500));
        bool? b = await Get.dialog(QsDialog.alert("余额不足，是否前往充值"));
        if (b == true) {
          Get.toNamed(Routes.myRecharge);
        }
      } else {
        Toast.text(result.data['m']);
      }
    } catch (error) {
      log(error.toString());
      Toast.text("购买失败，请重试");
    }
  }

  ///vip免费看
  static Future vipPlanPay(String? planId) async {
    final result = await DioUtils.post(
        "/${ApiDir.plan}/app-plan-do/vipPlanOrder",
        params: {"planId": planId},
        showLoading: true,
        showToast: false);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return true;
    }
    return false;
  }

  ///ai购买选项
  static Future<AiPayEntity> getAiPay(int type, {int? roomId}) async {
    final param = {"type": type, "roomId": roomId};
    final result =
        await DioUtils.post("/${ApiDir.ai}/app-ai-order/price", params: param);
    try {
      final data = AiPayEntity.fromJson(result.data["d"]);
      return data;
    } catch (e) {
      log(e.toString());
      return AiPayEntity();
    }
  }

  ///海外情报购买选项
  static Future<SecretPayEntity> getSecretPay({int? roomId}) async {
    final result = await DioUtils.post(
        "/${ApiDir.info}/app-reveal/revealPriceWithLive",
        params: {"id": roomId});
    try {
      final data = SecretPayEntity.fromJson(result.data["d"]);
      return data;
    } catch (e) {
      log(e.toString());
      return SecretPayEntity();
    }
  }

  ///VIP购买选项
  static Future<VipPayEntity> getVipPay({int? roomId}) async {
    final result = await DioUtils.post("/${ApiDir.user}/app-user-vip/vip",
        params: {"roomId": roomId});
    try {
      final data = VipPayEntity.fromJson(result.data["d"]);
      return data;
    } catch (e) {
      log(e.toString());
      return VipPayEntity();
    }
  }

  ///下单
  static Future<PayEntity?> generatePay(
      {String? itemId,
      double? payAmt,
      PayMode? payMode,
      bool showLoading = false}) async {
    final params = {
      "itemId": itemId ?? 0,
      "payAmt": payAmt ?? 0,
      "payType": payMode?.type,
      "userId": User.auth?.userId
    };
    final result = await DioUtils.post("/${ApiDir.user}/app-pay/create",
        params: params, showLoading: showLoading);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return PayEntity.fromJson(result.data["d"]);
    }
    return null;
  }

  ///充值补价直购
  static Future<PayEntity?> directPay(
      {double? buyCouponGold,
      String? buyCouponId,
      double? buyGold,
      String? buyId,
      int? buyType,
      double? payAmt,
      PayMode? payMode,
      bool showLoading = false}) async {
    final params = {
      "buyCouponGold": buyCouponGold,
      "buyCouponId": buyCouponId,
      "buyGold": buyGold,
      "buyId": buyId,
      "buyType": buyType,
      "payAmt": payAmt,
      "payType": payMode?.type
    };
    final result = await DioUtils.post("/${ApiDir.user}/app-pay/payBuy",
        params: params, showLoading: showLoading);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return PayEntity.fromJson(result.data["d"]);
    }
    return null;
  }

  ///验证ios内购
  static Future<int?> verifyIosPay(
      String? qxbOrderId, String receiptData, String productId) async {
    final params = {
      "qxbOrderId": qxbOrderId,
      "receiptDate": receiptData,
      "userId": User.auth?.userId,
      "productId": productId,
    };
    final result =
        await DioUtils.post("/${ApiDir.user}/usr-do/iosPay", params: params);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  static Future androidPay(PayMode? payMode, String certificate) async {
    if (payMode?.goAlipay ?? false) {
      AlipayKitPlatform.instance.pay(orderInfo: certificate);
    } else if (payMode?.goWechat ?? false) {
      Map<String, dynamic> wxParam = jsonDecode(certificate);
      String appId = wxParam["appid"] ?? "";
      String partnerId = wxParam["partnerid"] ?? "";
      String timestamp = wxParam["timestamp"] ?? "";
      String prepayId = wxParam["prepayid"] ?? "";
      String sign = wxParam["sign"] ?? "";
      String package = wxParam["package"] ?? "";
      String nonceStr = wxParam["noncestr"] ?? "";
      Fluwx().pay(
          which: Payment(
              appId: appId,
              partnerId: partnerId,
              prepayId: prepayId,
              packageValue: package,
              nonceStr: nonceStr,
              timestamp: timestamp.toInt() ?? 0,
              sign: sign));
    } else if (payMode?.goWeb ?? false) {
      Map<String, dynamic> param = jsonDecode(certificate);
      String url = param['appPayRequest']?['qrCode'];
      WebPay().pay(url);
    }
  }

  ///获取充值选项
  static Future<List<RechargeEntity>?> getRechargeList(
      String platformType) async {
    final params = {"platformType": platformType};
    final result = await DioUtils.post("/${ApiDir.user}/usr-do/payItem/rsp",
        params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      List<RechargeEntity> data = result.data["d"]
          .map<RechargeEntity>((e) => RechargeEntity.fromJson(e))
          .toList();
      return data;
    }
    return null;
  }

  ///我的订单
  static Future<List<OrderListEntity>?> orderList(
      PurchaseType type, int page, int pageSize) async {
    final data = {
      'data': {
        'userId': User.auth?.userId,
      },
      'page': page,
      'pageSize': pageSize
    };
    final result = await DioUtils.post(type.api, params: data);
    if (result.statusCode == 200 && result.data['c'] == 200) {
      List<OrderListEntity> data = [];
      if (type == PurchaseType.plan) {
        data = result.data['d']
            .map<OrderListEntity>((e) => OrderListEntity.fromViewpoint(e))
            .toList();
      } else if (type == PurchaseType.planForm) {
        data = result.data['d']
            .map<OrderListEntity>((e) => OrderListEntity.fromPlanForm(e))
            .toList();
      } else if (type == PurchaseType.couponPack) {
        data = result.data['d']
            .map<OrderListEntity>((e) => OrderListEntity.fromCouponPack(e))
            .toList();
      } else if (type == PurchaseType.subs) {
        data = result.data['d']
            .map<OrderListEntity>((e) => OrderListEntity.fromSubs(e))
            .toList();
      } else {
        data = result.data['d']
            .map<OrderListEntity>((e) => OrderListEntity.fromFeature(e))
            .toList();
      }
      return data;
    }
    return null;
  }

  ///金币明细列表
  static Future<List<CoinHistoryEntity>?> getCoinHistory(
      int page, int pageSize) async {
    final params = {
      "data": {"status": 2, "userId": User.auth?.userId},
      "page": page,
      "pageSize": pageSize
    };
    final result =
        await DioUtils.post("/${ApiDir.user}/usr-do/gold/list", params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      List<CoinHistoryEntity> data = result.data["d"]["rows"]
          .map<CoinHistoryEntity>((e) => CoinHistoryEntity.fromJson(e))
          .toList();
      return data;
    }
    return null;
  }

  ///金币明细详情
  static Future<CoinDetailEntity?> coinDetail(String id) async {
    final params = {
      "goldId": id,
      "userId": User.auth?.userId,
    };
    final result = await DioUtils.post("/${ApiDir.user}/usr-do/gold/detailInfo",
        params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return CoinDetailEntity.fromJson(result.data["d"]);
    }
    return null;
  }
}
